import React from "react";
import ReactDOM from 'react-dom';
import classNames from "classnames";
import { observer } from "mobx-react";
import DropMenu from './DropMenu';
import "./index.less";
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

@observer
export default class AppDesignerHeader extends React.Component {
  onTabChange = (tabKey) => {
    const { store } = this.props;
    store.onTabKeyChange(tabKey);
  }
  enterTab = (key, e) => {
    const { store } = this.props;
    if (key === 'excel' && store.excelPages.length > 1) {
      const { offsetLeft, offsetHeight, offsetTop } = e.target;
      this.showDropMenu(offsetLeft, offsetTop + offsetHeight);
    }
  }
  leaveTab = (key) => {
    if (key === 'excel') {
      const { store } = this.props;
      store.hideDropMenu();
    }
  }
  showDropMenu = (left, top) => {
    if (!this.dropMenu) {
      this.dropMenu = document.createElement('div');
      document.body.appendChild(this.dropMenu);
      this.dropMenu.className = "edc-drop-menu-wrapper";
      this.renderDropMenu();
    }
    const { store } = this.props;
    store.showDropMenu(left, top);
  }
  renderDropMenu = () => {
    const { store } = this.props;
    ReactDOM.render(<DropMenu store={store} />, this.dropMenu);
  }
  renderTabs = () => {
    const { store } = this.props;
    return store.tabs.map(({ key, text }) => (
      <li
        key={key}
        onClick={() => this.onTabChange(key)}
        className={classNames({ active: key === store.tabKey, 'with-down': key === 'excel' && store.excelPages.length > 1 })}
        onMouseEnter={this.enterTab.bind(this, key)}
        onMouseLeave={this.leaveTab.bind(this, key)}
      >
        {text}
      </li>
    ));
  }
  componentWillUnmount() {
    if (this.dropMenu) {
      ReactDOM.unmountComponentAtNode(this.dropMenu);
      document.body.removeChild(this.dropMenu);
      this.dropMenu = null;
    }
  }
  render() {
    const { store: { appName } } = this.props;
    return (
      <div className='wea-edc-header edc-ad-header'>
        <div className='logo wea-f14'>e-cology | {getLabel('502641', '数据中心')}</div>
        <div className='header-right'>
          <ul className='wea-f14'>
            {this.renderTabs()}
          </ul>
        </div>
        <div className="logo-right">{appName}</div>
      </div>
    );
  }
}
